<template>
    <el-dialog
        :title="title"
        append-to-body
        destroy-on-close
        :model-value="showDialog"
        @close="closeDialog()"
    >
        <!-- <span>{{ rowData }}</span> -->
        <!-- 表单 -->
        <el-form
            :model="form"
            ref="formRef"
            :rules="rules"
            :inline="false"
            label-width="120px"
        >
            <el-form-item label="名称" prop="name" class="role_edit_item">
                <el-input v-model="name" placeholder="" clearable></el-input>
            </el-form-item>
            <el-form-item label="角色编码" prop="code" class="role_edit_item">
                <el-input v-model="code" placeholder="" clearable></el-input>
            </el-form-item>
            <el-form-item label="权限" prop="menuIds" class="role_edit_item">
                <el-card
                    shadow="never"
                    :body-style="{
                        padding: 0,
                        height: '200px',
                        width: '100%',
                    }"
                    class="role_edit_item"
                >
                    <el-scrollbar style="width: 100%">
                        <el-tree
                            ref="tree"
                            :data="menuList"
                            node-key="id"
                            :props="{ label: 'name' }"
                            empty-text="暂无数据"
                            show-checkbox
                            highlight-current
                            :default-checked-keys="menuIds"
                        >
                            <template v-slot="{ data }">
                                <span
                                    :data-menuId="data.id"
                                    :class="{ ve_tree_item: data.type === 2 }"
                                >
                                    {{ data.name }}
                                </span>
                            </template>
                        </el-tree>
                    </el-scrollbar>
                    <!-- card body -->
                </el-card>
            </el-form-item>
            <el-form-item label="状态" prop="status" class="role_edit_item">
                <el-radio-group v-model="status">
                    <el-radio-button :label="true">启用</el-radio-button>
                    <el-radio-button :label="false">停用</el-radio-button>
                </el-radio-group>
            </el-form-item>
        </el-form>

        <template v-slot:footer>
            <span>
                <el-button @click="closeDialog()">取消</el-button>
                <el-button type="primary" @click="onSubmit()">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import {
    onMounted,
    reactive,
    ref,
    toRefs,
    nextTick,
    defineProps,
    defineEmits,
} from "vue";
import { treeFindPath } from "@/utils";
import { ElTree } from "element-plus";

const props = defineProps({
    showDialog: {
        type: Boolean,
        default: true,
    },
    title: {
        type: String,
        default: "添加",
    },
    rowData: {
        type: Object,
        default: null,
    },
});
const emit = defineEmits(["closeDialog"]);
const { title, rowData } = toRefs(props);
const closeDialog = () => {
    emit("closeDialog", false);
};
const form = reactive({
    code: "",
    name: "",
    menuIds: [],
    status: true,
});
const { code, name, menuIds, status } = toRefs(form);
const formRef = ref(null);
const rules = {
    name: [
        {
            required: true,
            message: "请输入名称",
            trigger: "blur",
        },
    ],
    code: [
        {
            required: true,
            message: "请输入角色编码",
            trigger: "blur",
        },
    ],
    menuIds: [
        {
            validator: (rule, value, callback) => {
                menuIds.value = [
                    // ...tree.value.getCheckedNodes(),
                    // ...tree.value.getHalfCheckedNodes(),
                    ...tree.value.getCheckedKeys(false),
                ];

                // console.log(menuIds.value);
                if (menuIds.value.length < 1) {
                    callback(new Error("请选择权限"));
                } else {
                    callback();
                }
            },
            required: true,
        },
    ],
};
const tree = ref(null);
const menuList = ref([]);

/**
 * @description: 数据初始化
 * @param {*}
 * @return {*}
 */
rowData.value &&
    ((name.value = rowData.value.name),
    (code.value = rowData.value.code),
    (status.value = rowData.value.status));
/**
 * @description:提交
 * @param {*}
 * @return {*}
 */
const onSubmit = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            let res;
            if (title.value === "添加") {
                res = await VE_API.system.roleAdd(form);
            } else {
                res = await VE_API.system.roleEdit({
                    id: rowData.value.id,
                    ...form,
                });
            }
            const { code } = res;
            if (code === 0) {
                closeDialog();
            }
        } else {
            console.log("error submit!!");
            return false;
        }
    });
};

/**
 * @description: 获取菜单数据
 * @param {*}
 * @return {*}
 */
const getMenuList = async () => {
    const { code, data } = await VE_API.system.menuList(
        {
            size: 10,
            page: 1,
            total: 0,
        },
        { Global: false },
    );
    if (code === 0) {
        const list = XE.mapTree(
            XE.toArrayTree(data, {
                sortKey: "sort",
                key: "code",
                parentKey: "parentCode",
            }),
            (item) => {
                if (item.children && item.children.length <= 0) {
                    delete item.children;
                }
                return item;
            },
        );
        menuList.value = list;
    }
};

/**
 * @description:改变按钮的排列样式
 * @param {*}
 * @return {*}
 */
const setMenuStyle = () => {
    let eles = document.getElementsByClassName("ve_tree_item");
    Array.from(eles).forEach((e) => {
        const roleId = e.dataset.roleid * 1;
        const index =
            treeFindPath(menuList.value, (item) => item.id === roleId).length -
            1;
        e.parentNode.parentNode.parentNode.style.paddingLeft =
            index * 18 + "px";
        let oldClass = e.parentNode.className;
        e.parentNode.className = oldClass + " fl p0";
    });
};
/**
 * 获取角色详情
 */
onMounted(async () => {
    await getMenuList();
    nextTick(async () => {
        setMenuStyle();
        if (title.value === "添加") {
            // console.log(menuList.value);
            tree.value.setCheckedNodes(menuList.value);
        } else {
            const { code, data } = await VE_API.system.roleOne({
                id: rowData.value.id,
            });
            // debugger;
            // console.log(code);
            if (code === 0) {
                const list = XE.mapTree(
                    XE.toArrayTree(data.menuList, {
                        sortKey: "sort",
                        key: "code",
                        parentKey: "parentCode",
                    }),
                    (item) => {
                        if (item.children && item.children.length <= 0) {
                            delete item.children;
                        }
                        return item;
                    },
                );
                console.log(list);
                if (list && list.length > 0) {
                    tree.value.setCheckedNodes(list);
                }
            }
        }
    });
});
</script>

<style lang="scss">
.fl {
    float: left;
}
.p0 {
    padding: 0 !important;
}
.role_edit_item {
    width: 100%;
}
</style>
